<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,100分)- 找数字、找等值元素（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>给一个二维数组nums&#xff0c;对于每一个元素nums[i]&#xff0c;找出距离最近的且值相等的元素&#xff0c;输出横纵坐标差值的绝对值之和&#xff0c;如果没有等值元素&#xff0c;则输出-1。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>输入第一行为二维数组的行<br /> 输入第二行为二维数组的列<br /> 输入的数字以空格隔开。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>数组形式返回所有坐标值。</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">3<br /> 5<br /> 0 3 5 4 2<br /> 2 5 7 8 3<br /> 2 5 4 2 4</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">[[-1, 4, 2, 3, 3], [1, 1, -1, -1, 4], [1, 1, 2, 3, 2]]</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">无</td></tr></tbody></table> 
<p></p> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>我的解题思路如下&#xff1a;</p> 
<p>首先遍历输入的矩阵&#xff0c;将相同数字的位置整理到一起。</p> 
<p>然后再遍历一次输入的矩阵&#xff0c;找到和遍历元素相同的其他数字&#xff08;通过上一步统计结果快速找到&#xff09;&#xff0c;求距离&#xff0c;并保留最小的距离。</p> 
<p></p> 
<p>上面逻辑的算法复杂度为O(n*m*k)&#xff0c;其中n是输入矩阵行&#xff0c;m是输入矩阵列&#xff0c;k是每组相同数字的个数&#xff0c;可能会达到O(N^3)的时间复杂度。</p> 
<p></p> 
<p>有一个优化点就是&#xff0c;遍历元素A找其他相同数字B时计算的距离可以缓存&#xff0c;这样的话&#xff0c;当遍历元素B时找其他相同数字A时&#xff0c;就可以从缓存中读取已经计算好的距离了&#xff0c;而不是重新计算。但是这样会浪费较多空间。</p> 
<p>实际机试时&#xff0c;可以看用例数量级来决定是否要做上面这个优化。如果数量级很小&#xff0c;则无需上面优化。如果数量级较大&#xff0c;则有优化的必要。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n, m;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 2) {
    n &#61; lines[0] - 0;
    m &#61; lines[1] - 0;
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 2) {
    const matrix &#61; lines.slice(2).map((line) &#61;&gt; line.split(&#34; &#34;).map(Number));
    console.log(getResult(matrix, n, m));
    lines.length &#61; 0;
  }
});

function getResult(matrix, n, m) {
  const nums &#61; {};

  // 统计输入矩阵中&#xff0c;相同数字的位置
  for (let i &#61; 0; i &lt; n; i&#43;&#43;) {
    for (let j &#61; 0; j &lt; m; j&#43;&#43;) {
      const num &#61; matrix[i][j];
      nums[num] ? nums[num].push([i, j]) : (nums[num] &#61; [[i, j]]);
    }
  }

  // 遍历矩阵每一个元素&#xff0c;和其他相同数字的位置求距离&#xff0c;&#xff0c;取最小距离
  for (let i &#61; 0; i &lt; n; i&#43;&#43;) {
    for (let j &#61; 0; j &lt; m; j&#43;&#43;) {
      const num &#61; matrix[i][j];

      let minDis &#61; Infinity;
      nums[num].forEach((pos) &#61;&gt; {
        const [i1, j1] &#61; pos;
        if (i1 !&#61;&#61; i || j1 !&#61;&#61; j) {
          let dis &#61; Math.abs(i1 - i) &#43; Math.abs(j1 - j);
          minDis &#61; Math.min(minDis, dis);
        }
      });

      matrix[i][j] &#61; minDis &#61;&#61;&#61; Infinity ? -1 : minDis;
    }
  }

  return JSON.stringify(matrix).replace(/,/g, &#34;, &#34;);
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();
    int m &#61; sc.nextInt();

    int[][] matrix &#61; new int[n][m];
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      for (int j &#61; 0; j &lt; m; j&#43;&#43;) {
        matrix[i][j] &#61; sc.nextInt();
      }
    }

    System.out.println(getResult(matrix, n, m));
  }

  public static String getResult(int[][] matrix, int n, int m) {
    HashMap&lt;Integer, ArrayList&lt;Integer[]&gt;&gt; nums &#61; new HashMap&lt;&gt;();

    // 统计输入矩阵中&#xff0c;相同数字的位置
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      for (int j &#61; 0; j &lt; m; j&#43;&#43;) {
        Integer num &#61; matrix[i][j];
        Integer[] arr &#61; {i, j};
        nums.putIfAbsent(num, new ArrayList&lt;&gt;());
        nums.get(num).add(arr);
      }
    }

    // 遍历矩阵每一个元素&#xff0c;和其他相同数字的位置求距离&#xff0c;&#xff0c;取最小距离
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      for (int j &#61; 0; j &lt; m; j&#43;&#43;) {
        int num &#61; matrix[i][j];

        int minDis &#61; Integer.MAX_VALUE;
        for (Integer[] pos : nums.get(num)) {
          int i1 &#61; pos[0];
          int j1 &#61; pos[1];

          if (i1 !&#61; i || j1 !&#61; j) {
            int dis &#61; Math.abs(i1 - i) &#43; Math.abs(j1 - j);
            minDis &#61; Math.min(minDis, dis);
          }
        }

        matrix[i][j] &#61; minDis &#61;&#61; Integer.MAX_VALUE ? -1 : minDis;
      }
    }

    return Arrays.toString(Arrays.stream(matrix).map(Arrays::toString).toArray(String[]::new));
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())
m &#61; int(input())
matrix &#61; [list(map(int, input().split())) for i in range(n)]


# 算法入口
def getResult(matrix, n, m):
    nums &#61; {}

    # 统计输入矩阵中&#xff0c;相同数字的位置
    for i in range(n):
        for j in range(m):
            num &#61; matrix[i][j]
            if nums.get(num) is None:
                nums[num] &#61; [[i, j]]
            else:
                nums[num].append([i, j])

    # 遍历矩阵每一个元素&#xff0c;和其他相同数字的位置求距离&#xff0c;取最小距离
    for i in range(n):
        for j in range(m):
            num &#61; matrix[i][j]

            minDis &#61; None
            for i1, j1 in nums[num]:
                if i1 !&#61; i or j1 !&#61; j:
                    dis &#61; abs(i1 - i) &#43; abs(j1 - j)
                    if minDis is None:
                        minDis &#61; dis
                    else:
                        minDis &#61; min(minDis, dis)

            matrix[i][j] &#61; -1 if minDis is None else minDis

    return matrix


# 调用算法
print(getResult(matrix, n, m))
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>